package com.wzt.gift.handler;

import com.wzt.gift.exception.BusinessException;
import com.wzt.gift.util.AjaxResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

/**
 * @Author Zenith
 * @Date 2022/10/11 16:30
 * @Version 1.0
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    @ExceptionHandler(BusinessException.class)
    public AjaxResult businessExceptionHandler(BusinessException e) {
        log.error("ERROR!" + e.getMessage());
        return AjaxResult.me().setSuccess(false).setMessage("错误码" + e.getCode() + ":" + e.getMessage());
    }

    @ExceptionHandler(Exception.class)
    public AjaxResult exceptionHandler(Exception e) {
        log.error("ERROR!" + e.getMessage());
        e.printStackTrace();
        return AjaxResult.me().setSuccess(false).setMessage("系统异常！" + e.getMessage());
    }
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public AjaxResult methodArgNotValid(MethodArgumentNotValidException e) {
        List<FieldError> fieldErrors = e.getBindingResult().getFieldErrors();
        StringBuffer sb = new StringBuffer();
        // 遍历所有字段异常
        fieldErrors.forEach(fieldError -> {
            // 拼接错误信息
            sb.append(fieldError.getDefaultMessage() + ",");
        });
        String s = sb.toString();
        // 去除掉最后一个逗号
        String resultMeg = s.substring(0, s.length() - 1);
        resultMeg += "!";

        log.error("ERROR!" + resultMeg);
        return AjaxResult.me().setSuccess(false).setMessage(resultMeg);
    }
}
